//
//  XGRecommendUserView.swift
//  TodayNews
//
//  Created by monkey on 2020/2/20.
//  Copyright © 2020 itcast. All rights reserved.
//

import UIKit

// MARK: - XGRecommendUserView

class XGRecommendUserView: UIView
{
    /// 推荐用户数组
    var userCards: [XGUserCardModel]? {
        didSet {
            collectionView.reloadData()
        }
    }
    /// 视图模型
    var userDetailViewModel: XGUserDetailViewModel?
    
    override init(frame: CGRect)
    {
        super.init(frame: frame)
        setUpUI()
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    override func layoutSubviews()
    {
        super.layoutSubviews()
        
        if bounds.height > 0 {
            titleLabel.origin = CGPoint(x: 10, y: 5)
            collectionView.frame = CGRect(x: 0, y: titleLabel.frame.maxY + 10, width: bounds.width, height: ceil(bounds.height - titleLabel.frame.maxY - 10 - 10))
        }        
    }

    private lazy var titleLabel: UILabel = UILabel(text: "相关推荐", textColor: UIColor.darkGray, fontSize: 17, textAlignment: .left)
    private lazy var collectionView: UICollectionView = {
        let collectionView = UICollectionView(frame: CGRect.zero, collectionViewLayout: XGRecommendUserCollectionViewFlowLayout())
        collectionView.backgroundColor = UIColor(white: 0.95, alpha: 1)
        collectionView.showsHorizontalScrollIndicator = false
        collectionView.dataSource = self
        collectionView.delegate = self
        collectionView.xg_registerCell(cellType: XGRecommendUserCollectionViewCell.self)
        return collectionView
    }()
}

// MARK: collecitonView数据源和代理

extension XGRecommendUserView: UICollectionViewDataSource, UICollectionViewDelegate
{
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int
    {
        return userCards?.count ?? 0
    }
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell
    {
        let cell = collectionView.xg_dequeueReusableCell(indexPath: indexPath) as XGRecommendUserCollectionViewCell
        cell.userCard = userCards?[indexPath.item]
        cell.userDetailViewModel = userDetailViewModel
        return cell
    }
}

// MARK: 私有扩展

private extension XGRecommendUserView
{
    func setUpUI() -> Void
    {
        clipsToBounds = true
        backgroundColor = UIColor(white: 0.95, alpha: 1)
        addSubview(titleLabel)
        addSubview(collectionView)
    }
}

// MARK: - XGRecommendUserCollectionViewFlowLayout

private class XGRecommendUserCollectionViewFlowLayout: UICollectionViewFlowLayout
{
    override func prepare()
    {
        super.prepare()
        
        scrollDirection = .horizontal
        itemSize = CGSize(width: 150, height: collectionView?.bounds.height ?? 0)
        minimumLineSpacing = 10
        sectionInset = UIEdgeInsets(top: 0, left: 10, bottom: 0, right: 10)
    }
} 
